from datetime import datetime
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
import pymysql
import uuid
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql+pymysql://root:123456@192.168.0.115:3306/tornado?charset=utf8')
# 创建模型对象基类
BaseModel = declarative_base()


class User(BaseModel):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(100), unique=True, nullable=False)
    password = Column(String(100), nullable=False)
    email = Column(String(100), unique=True)
    user_type = Column(Integer, default=1, comment='用户类型')
    create_time = Column(DateTime, default=datetime.now())
    is_lock = Column(Boolean, default=False, comment='账号状态')
    icon = Column(String(255), default='image/icon/default.png')

    def __repr__(self):
        return self.username


class ChatRecord(BaseModel):
    __tablename__ = 'chatrecord'

    id = Column(Integer, primary_key=True, autoincrement=True)
    who_send = Column(Integer, ForeignKey('user.id'), comment='消息发送者')
    who_recv = Column(Integer, ForeignKey('user.id'), comment='消息接收者')
    message = Column(String(255), nullable=False, comment='消息内容')
    send_time = Column(DateTime, default=datetime.now(), comment='消息发送时间')


class Classify(BaseModel):
    __tablename__ = 'classify'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(100), unique=True, nullable=False)

    def __repr__(self):
        return self.name


class Goods(BaseModel):
    __tablename__ = 'goods'

    id = Column(Integer, primary_key=True, autoincrement=True)
    code = Column(String(100), default=uuid.uuid4().int, comment='商品编号')
    name = Column(String(255), nullable=False, comment='商品名称')
    price = Column(Float(precision=2), nullable=False, comment='价格，保留两位')
    seller = Column(Integer, ForeignKey('user.id'), comment='发布者（卖家）')
    desc = Column(String(1000), comment='描述')
    serves = Column(String(100), comment='提供服务，1:退补；2:7天；3:包邮；4:72小时发货')
    classify = Column(Integer, ForeignKey('classify.id'), comment='类别')
    status = Column(Boolean, default=True, comment='发布状态')
    images = Column(String(1000), default='', comment='图片路径')
    create_time = Column(DateTime, default=datetime.now(), comment='创建时间')

    def __repr__(self):
        return self.name


def init_db():
    BaseModel.metadata.create_all(engine)


def drop_db():
    BaseModel.metadata.drop_all(engine)


# 创建session对象
Session = sessionmaker(bind=engine)
session = Session()

if __name__ == '__main__':
    init_db()
